package com.design.singleton;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;


/***
 * 序列化的单例
 * @author cWX241319
 *
 *Despction : 序列化是将实例对象写到磁盘实现数据的持久化或者进行数据的远程传输，当单例对象实现Serializable序列化时，即便将构造函数设为私有，
 				在它反序列化时依然会通过特殊的途径创建一个类的新实例对象相当于调用了该类的构造函数有效地获得了一个新实例！
 */
public class SerializableSingleton implements Serializable{

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 7267887267316805535L;
	
	
	private static final SerializableSingleton singleton = new SerializableSingleton();
	
	private SerializableSingleton() {};
	
	public static SerializableSingleton getSerializableSingleton() {
		
		return singleton;
	}
	
	/***
	 * 通过重写Serializable接口的readResolve方法来控制反序列化，在方法中可以返回单例的实例代替从读取流新建的实例对象，就可以防止序列化破坏单例
	 * @return
	 */
	private Object readResolve() {
		
		return singleton;
	}
	
	
	public static void main(String[] args) {
		
		SerializableSingleton singleton1 = SerializableSingleton.getSerializableSingleton();
		
		SerializableSingleton singleton2 = SerializableSingleton.getSerializableSingleton();
		
		System.out.println(singleton1 == singleton2);
		
		File file = new File("../aSingleton.txt");
		
		try {
			
			
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
			oos.writeObject(singleton1);
			oos.close();
			
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
			SerializableSingleton singleton3 = (SerializableSingleton) ois.readObject();
			
			
			System.out.println(singleton1 == singleton3);
			
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}
